package com.growthsee.rider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.growthsee.common.core.domain.AjaxResult;
import com.growthsee.common.utils.SecurityUtils;
import com.growthsee.common.utils.StringUtils;
import com.growthsee.rider.constant.ConstantConfig;
import com.growthsee.rider.domain.RiderInfo;
import com.growthsee.rider.enumeration.StatusEnum;
import com.growthsee.rider.enumeration.YesNoEnum;
import com.growthsee.rider.mapper.RiderInfoMapper;
import com.growthsee.rider.service.RiderInfoService;
import com.growthsee.rider.wrapper.RiderWrapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author csy
 * @since 2021-05-13
 */
@Service
public class RiderInfoServiceImpl extends ServiceImpl<RiderInfoMapper, RiderInfo> implements RiderInfoService {
    private static Lock lock = new ReentrantLock(false);
    @Override
    public AjaxResult addWxMpUser(RiderInfo riderInfo) {
        String check = RiderWrapper.builder().check(riderInfo);
        if(StringUtils.isNotEmpty(check)){
            return AjaxResult.error(check);
        }
        riderInfo.setCreateBy(riderInfo.getOpenId());
        riderInfo.setCreateTime(new Date());
        riderInfo.setStatus(StatusEnum.ENABLE.getValue());
        riderInfo.setDeleted(YesNoEnum.NO.getValue());
        baseMapper.insert(riderInfo);
        return AjaxResult.success();
    }

    @Override
    public String updateScore(Long userId, BigDecimal removeScore, BigDecimal addScore) {
        RiderInfo riderInfo = baseMapper.selectOne(Wrappers.<RiderInfo>lambdaQuery().eq(RiderInfo::getUserId,userId));
        update(Wrappers.<RiderInfo>lambdaUpdate()
                .set(RiderInfo::getCumulativeScore,riderInfo.getCumulativeScore().subtract(removeScore))
                .set(RiderInfo::getCurrentQuarterRemoveScore,riderInfo.getCurrentQuarterRemoveScore().add(removeScore))
                .eq(RiderInfo::getUserId,userId)
        );
        return "";
    }

    @Override
    public void updateStatus(String userId) {
        RiderInfo riderInfo = baseMapper.selectOne(Wrappers.<RiderInfo>lambdaQuery().eq(RiderInfo::getUserId,userId));
        int status = StatusEnum.ENABLE.getValue();
        if(riderInfo.getCumulativeScore().compareTo(new BigDecimal(ConstantConfig.POINTS_ONLINE))==1)status=StatusEnum.DISABLE.getValue();
        lock.lock();
        update(Wrappers.<RiderInfo>lambdaUpdate()
                .set(RiderInfo::getStatus,status)
                .eq(RiderInfo::getUserId,userId));
    }
}
